<template>
  <div class="role-manage-page">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button @click="handleBatch">批量操作</el-button>
      <el-button @click="handleExport">导出</el-button>
      <el-input
        v-model="searchKey"
        placeholder="请输入角色名称搜索"
        style="width: 200px; margin-left: 20px;"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 角色表格 -->
    <el-table
      :data="roleList"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="roleId" label="角色ID" width="100"></el-table-column>
      <el-table-column prop="roleName" label="角色名称" width="120"></el-table-column>
      <el-table-column prop="deptName" label="所属部门" width="220"></el-table-column>
      <el-table-column label="角色状态" width="120">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="启用"
            inactive-value="禁用"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="userCount" label="员工人数" width="100"></el-table-column>
      <el-table-column prop="createTime" label="时间" width="160"></el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)" style="color: #F56C6C;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px;"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      title="角色信息"
      :visible.sync="dialogVisible"
      width="400px"
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <treeselect
            v-model="form.deptId"
            :options="deptOptions"
            :normalizer="normalizer"
            placeholder="请选择所属部门"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="启用" value="启用"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员 工人数" prop="userCount">
          <el-input-number v-model="form.userCount" :min="0" placeholder="请输入员工人数" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script>
import {
  getRoleList,
  addRole,
  editRole,
  deleteRole,
  changeRoleStatus,
  exportRole
} from '@/api/tms/set/role';
import { treeSelect }from '@/api/tms/set/department';
import Treeselect from "@riophae/vue-treeselect";
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import * as XLSX from 'xlsx';

export default {
  name: 'Role',
  components: {
    Treeselect
  },
  data() {
    return {
      roleList: [],        // 角色列表数据
      searchKey: '',       // 模糊搜索角色名称
      pageNum: 1,          // 当前页码
      pageSize: 10,        // 每页条数
      total: 100,          // 总数据条数（示例值）
      dialogVisible: false,// 弹窗显隐
      form: {
        roleId: '',        // 角色ID
        roleName: '',      // 角色名称
        deptId: undefined, // 所属部门ID
        status: '启用',    // 角色状态，默认为启用
        userCount: 0       // 员工人数，默认为0
      },                   // 弹窗表单数据，预先定义所有字段
      formRules: {         // 表单校验规则
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        deptId: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
        status: [{ required: true, message: '请选择角色状态', trigger: 'change' }],
        userCount: [{ required: true, message: '请输入员工人数', trigger: 'blur' }],

      },
      selectedRows: [],    // 表格选中行
      isEdit: false,       // 标识：新增/编辑模式
      deptOptions: [],     // 部门选项列表
      deptId: undefined    // 部门ID
    };
  },
  created() {
    this.fetchRoleList(); // 初始化加载角色列表
    this.fetchDepartmentTree(); // 获取部门树形结构
  },
  methods: {
    normalizer(node) {
      return {
        id: node.id,
        label: node.label,
        children: node.children,
        //deptName: node.deptName
      };
    },
    // 获取角色列表（对接后端接口）
    fetchRoleList() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        keyword: this.searchKey,
      };
      getRoleList(params).then(res => {
        this.roleList = res;
      });
    },

    // 获取部门树形结构
    fetchDepartmentTree() {
        treeSelect().then(res => {
          console.log('部门树形数据:', res.data);
          // 确保数据格式正确，添加空数组默认值
          this.deptOptions = res.data || [];
          // 处理可能的空children情况
          this.deptOptions = this.deptOptions.map(node => ({
            ...node,
            children: node.children || []
          }));
          console.log('处理后的部门选项:', this.deptOptions);
          // 如果没有数据，给用户提示
          if (this.deptOptions.length === 0) {
            this.$message.warning('未获取到部门数据，请联系管理员');
          }
        }).catch(error => {
          console.error('获取部门树形数据失败:', error);
          this.$message.error('部门数据加载失败，请刷新页面重试');
        });
      },

    // 搜索操作
    handleSearch() {
      this.pageNum = 1;
      this.fetchRoleList();
    },

    // 重置搜索
    handleReset() {
      this.searchKey = '';
      this.pageNum = 1;
      this.fetchRoleList();
    },

    // 分页-每页条数变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.fetchRoleList();
    },

    // 分页-当前页变化
    handleCurrentChange(val) {
      this.pageNum = val;
      this.fetchRoleList();
    },

    // 表格选中行变化
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    // 新增角色
    handleAdd() {
      this.isEdit = false;
      this.form = {
        deptId: undefined
      };
      this.dialogVisible = true;
    },

    // 编辑角色
    handleEdit(row) {
      this.isEdit = true;
      this.form = {
        roleId: row.roleId,
        roleName: row.roleName,
        deptId: row.deptId,
        status: row.status,
        userCount: row.userCount
      };
      this.dialogVisible = true;
    },

    // 删除角色（带二次确认）
    handleDelete(row) {
      this.$confirm(`确定删除角色【${row.roleName}】吗？`, '提示', { type: 'warning' })
        .then(() => {
          deleteRole(row.roleId).then(() => {
            this.$message.success('删除成功');
            this.fetchRoleList();
          });
        })
        .catch(() => {});
    },

    // 批量操作（示例，需根据业务扩展）
    handleBatch() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$message.info(`批量操作选中了 ${this.selectedRows.length} 条数据`);
    },

    // 导出角色列表
    handleExport() {
      // 使用前端数据导出，不依赖后端接口
      this.$confirm('确定要导出角色数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        try {
          // 准备导出的数据，只包含需要的字段
          const exportData = this.roleList.map(row => ({
            '角色ID': row.roleId,
            '角色名称': row.roleName,
            '所属部门': row.deptName,
            '角色状态': row.status,
            '员工人数': row.userCount,
            '创建时间': row.createTime
          }));

          // 创建工作簿和工作表
          const wb = XLSX.utils.book_new();
          const ws = XLSX.utils.json_to_sheet(exportData);

          // 添加工作表到工作簿
          XLSX.utils.book_append_sheet(wb, ws, '角色列表');

          // 导出Excel文件
          XLSX.writeFile(wb, '角色列表.xlsx');

          this.$message.success('导出成功');
        } catch (error) {
          console.error('导出失败:', error);
          this.$message.error('导出失败，请重试');
        }
      }).catch(() => {});
    },

    // 角色状态切换（对接后端接口）
    handleStatusChange(row) {
      changeRoleStatus(row.roleId, row.status).then(() => {
        this.$message.success('状态更新成功');
      }).catch(() => {
        // 接口失败时回滚状态
        row.status = row.status === '启用' ? '禁用' : '启用';
      });
    },

    // 弹窗表单提交（新增/编辑）
    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const requestFn = this.isEdit ? editRole : addRole;
          requestFn(this.form).then(() => {
            this.$message.success(this.isEdit ? '编辑成功' : '新增成功');
            this.dialogVisible = false;
            this.fetchRoleList(); // 刷新列表
          });
        }
      });
    },
  },
};
</script>


<style scoped>
.role-manage-page {
  padding: 16px;
  background-color: #fff;
}
.operation-bar {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}
</style>
